package clusterrole

import (
	rbacv1 "k8s.io/api/rbac/v1"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/informers"
	"kubeconsole/api"
	"kubeconsole/apiserver/query"
	"kubeconsole/models/resources/v1alpha3"
)

type rolesGetter struct {
	sharedInformers informers.SharedInformerFactory
}

func New(sharedInformers informers.SharedInformerFactory) v1alpha3.Interface {
	return &rolesGetter{sharedInformers: sharedInformers}
}

func (d *rolesGetter) Get(namespace, name string) (runtime.Object, error) {
	return d.sharedInformers.Rbac().V1().ClusterRoles().Lister().Get(name)
}

func (d *rolesGetter) List(namespace string, query *query.Query) (*api.ListResult, error) {

	all, err := d.sharedInformers.Rbac().V1().ClusterRoles().Lister().List(query.Selector())
	if err != nil {
		return nil, err
	}

	var result []runtime.Object
	for _, deploy := range all {
		result = append(result, deploy)
	}

	return v1alpha3.DefaultList(result, query, d.compare, d.filter), nil
}

func (d *rolesGetter) compare(left runtime.Object, right runtime.Object, field query.Field) bool {

	leftRole, ok := left.(*rbacv1.ClusterRole)
	if !ok {
		return false
	}

	rightRole, ok := right.(*rbacv1.ClusterRole)
	if !ok {
		return false
	}

	return v1alpha3.DefaultObjectMetaCompare(leftRole.ObjectMeta, rightRole.ObjectMeta, field)
}

func (d *rolesGetter) filter(object runtime.Object, filter query.Filter) bool {
	role, ok := object.(*rbacv1.ClusterRole)

	if !ok {
		return false
	}

	return v1alpha3.DefaultObjectMetaFilter(role.ObjectMeta, filter)
}
